import { defineStore } from 'pinia';
import { ref } from 'vue';
import trackingAPI from '../api/tracking.api';

// 有效的时间范围选项
const VALID_TIME_RANGES = ['today', 'yesterday', 'last_7_days', 'last_30_days', 'this_month', 'last_month', 'custom'];

/**
 * 网站跟踪状态管理
 * 使用Pinia实现状态管理
 */
export const useTrackingStore = defineStore('tracking', () => {
  // 状态
  const websites = ref<any[]>([]);
  const currentWebsite = ref<any>(null);
  const websiteStats = ref<any>(null);
  const businessLoopLogs = ref<any>(null);
  const businessLoopIntegrity = ref<any>(null);
  const logStats = ref<any>(null);
  const isLoading = ref<boolean>(false);
  const error = ref<string | null>(null);
  const statsParams = ref<{ timeRange: string; groupBy: string }>({ 
    timeRange: 'last_7_days', 
    groupBy: 'day' 
  });

  // 获取网站列表
  const fetchWebsites = async () => {
    isLoading.value = true;
    error.value = null;
    try {
      const response = await trackingAPI.getWebsites();
      // 处理不同的响应格式：可能是数组、对象包含data属性、或对象包含data数组
      let websitesData: any[] = [];
      if (Array.isArray(response)) {
        websitesData = response;
      } else if (response?.data && Array.isArray(response.data)) {
        websitesData = response.data;
      } else if (response?.data && !Array.isArray(response.data)) {
        websitesData = [response.data];
      } else {
        websitesData = [];
      }
      
      websites.value = websitesData;
      isLoading.value = false;
      return websitesData;
    } catch (err: any) {
      error.value = err.message || '获取网站列表失败';
      isLoading.value = false;
      throw err;
    }
  };

  // 创建网站
  const createWebsite = async (websiteData: any) => {
    isLoading.value = true;
    error.value = null;
    try {
      const response = await trackingAPI.createWebsite(websiteData);
      // 处理不同的响应格式
      const website = response?.data || response;
      if (website) {
        websites.value.push(website);
        if (!currentWebsite.value) {
          currentWebsite.value = website;
        }
      }
      isLoading.value = false;
      return website;
    } catch (err: any) {
      error.value = err.message || '创建网站失败';
      isLoading.value = false;
      throw err;
    }
  };

  // 更新网站
  const updateWebsite = async (id: string | number, websiteData: any) => {
    isLoading.value = true;
    error.value = null;
    try {
      const response = await trackingAPI.updateWebsite(id, websiteData);
      // 处理不同的响应格式
      const updatedWebsite = response?.data || response;
      if (updatedWebsite) {
        const index = websites.value.findIndex((w: any) => w._id === id);
        if (index !== -1) {
          websites.value[index] = updatedWebsite;
        }
        if (currentWebsite.value?._id === id) {
          currentWebsite.value = updatedWebsite;
        }
      }
      isLoading.value = false;
      return updatedWebsite;
    } catch (err: any) {
      error.value = err.message || '更新网站失败';
      isLoading.value = false;
      throw err;
    }
  };

  // 删除网站
  const deleteWebsite = async (id: string | number) => {
    isLoading.value = true;
    error.value = null;
    try {
      await trackingAPI.deleteWebsite(id);
      const index = websites.value.findIndex((w: any) => w._id === id);
      if (index !== -1) {
        websites.value.splice(index, 1);
      }
      if (currentWebsite.value?._id === id) {
        currentWebsite.value = websites.value.length > 0 ? websites.value[0] : null;
        websiteStats.value = null;
      }
      isLoading.value = false;
    } catch (err: any) {
      error.value = err.message || '删除网站失败';
      isLoading.value = false;
      throw err;
    }
  };

  // 删除所有网站
  const deleteAllWebsites = async () => {
    isLoading.value = true;
    error.value = null;
    try {
      await trackingAPI.deleteAllWebsites();
      websites.value = [];
      currentWebsite.value = null;
      websiteStats.value = null;
      businessLoopLogs.value = null;
      businessLoopIntegrity.value = null;
      isLoading.value = false;
    } catch (err: any) {
      error.value = err.message || '删除所有网站失败';
      isLoading.value = false;
      throw err;
    }
  };

  // 设置当前网站
  const setCurrentWebsite = (website: any) => {
    currentWebsite.value = website;
  };

  // 更新统计参数
  const updateStatsParams = (params: any) => {
    // 验证timeRange参数
    if (params.timeRange && !VALID_TIME_RANGES.includes(params.timeRange)) {
      console.warn(`Invalid timeRange: ${params.timeRange}. Using default: last_7_days`);
      params.timeRange = 'last_7_days';
    }
    
    statsParams.value = { ...statsParams.value, ...params };
    // 不在这里调用fetchWebsiteStats，让watch来处理
  };

  // 获取网站统计
  const fetchWebsiteStats = async (websiteId: string | number, params: any = {}) => {
    isLoading.value = true;
    error.value = null;
    try {
      // 验证并清理参数
      if (params.timeRange && !VALID_TIME_RANGES.includes(params.timeRange)) {
        console.warn(`Invalid timeRange: ${params.timeRange}. Using default: last_7_days`);
        params.timeRange = 'last_7_days';
      }
      
      const response = await trackingAPI.getWebsiteStats(websiteId, params);
      
      // axios 响应拦截器已经返回了 response.data，所以 response 应该已经是数据本身
      // 但为了兼容性，仍然检查是否有嵌套的 data
      let stats: any = null;
      if (response && typeof response === 'object') {
        // 如果 response 有 data 属性且是对象，可能是包装的响应
        if ('data' in response && response.data && typeof response.data === 'object' && !Array.isArray(response.data)) {
          stats = (response as any).data;
        } 
        // 如果 response 本身就有我们需要的字段，直接使用
        else if ('summary' in response || 'data' in response || 'referrers' in response) {
          stats = response;
        }
        // 如果 response.data 存在且是我们需要的数据
        else if ((response as any).data) {
          stats = (response as any).data;
        } else {
          stats = response;
        }
      }
      
      // 确保数据结构完整，即使某些字段缺失也提供默认值
      if (stats) {
        // 规范化数据字段：后端可能返回 referrer/device/browser/os/country/url，但组件期望的是完整的对象
        const normalizeArray = (arr: any[], key: string) => {
          if (!Array.isArray(arr)) return [];
          return arr.map((item: any) => {
            // 处理不同的字段名
            const value = item[key] || item[Object.keys(item)[0]] || null;
            return {
              [key]: value,
              count: Number(item.count) || 0,
              ...item
            };
          });
        };
        
        websiteStats.value = {
          summary: stats.summary || { totalPageViews: 0, uniquePageViews: 0, bounceRate: 0 },
          data: Array.isArray(stats.data) ? stats.data : [],
          referrers: normalizeArray(stats.referrers, 'referrer'),
          devices: normalizeArray(stats.devices, 'device'),
          browsers: normalizeArray(stats.browsers, 'browser'),
          os: normalizeArray(stats.os, 'os'),
          countries: normalizeArray(stats.countries, 'country'),
          urls: normalizeArray(stats.urls, 'url')
        };
      } else {
        websiteStats.value = null;
      }
      
      isLoading.value = false;
      return websiteStats.value;
    } catch (err: any) {
      console.error('[TrackingStore] Error fetching stats:', err);
      error.value = err.message || '获取网站统计数据失败';
      isLoading.value = false;
      // 即使失败也设置一个空值，避免显示旧数据
      websiteStats.value = null;
      throw err;
    }
  };

  // 获取嵌入代码
  const getEmbedCode = async (websiteId: string | number) => {
    isLoading.value = true;
    error.value = null;
    try {
      const response = await trackingAPI.getEmbedCode(websiteId);
      // 处理不同的响应格式
      const embedCode = response?.data || response || null;
      isLoading.value = false;
      return embedCode;
    } catch (err: any) {
      error.value = err.message || '获取嵌入代码失败';
      isLoading.value = false;
      throw err;
    }
  };

  // 获取今日日志统计
  const fetchLogStats = async (params: any = {}) => {
    isLoading.value = true;
    error.value = null;
    try {
      // 添加默认参数，可能后端需要日期范围和网站ID
      const defaultParams = {
        date: new Date().toISOString().split('T')[0], // 今天的日期
        websiteId: currentWebsite.value?._id, // 当前网站ID
        ...params
      };
      const response = await trackingAPI.getLogStats(defaultParams);
      // 处理不同的响应格式
      const stats = response?.data || response || null;
      logStats.value = stats;
      isLoading.value = false;
      return stats;
    } catch (err: any) {
      error.value = err.message || '获取日志统计失败';
      isLoading.value = false;
      logStats.value = null;
      throw err;
    }
  };

  // 获取业务闭环记录
  const fetchBusinessLoopLogs = async (websiteId: string | number, date?: string) => {
    // 不设置全局 isLoading，避免影响其他加载状态
    error.value = null;
    try {
      const response = await trackingAPI.getBusinessLoopLogs(websiteId, date);
      // 处理不同的响应格式：可能是数组或包含data属性的对象
      let logs: any[] | null = null;
      if (Array.isArray(response)) {
        logs = response;
      } else if (response?.data && Array.isArray(response.data)) {
        logs = response.data;
      } else if (response?.data) {
        logs = [response.data];
      } else {
        logs = [];
      }
      businessLoopLogs.value = logs;
      return logs;
    } catch (err: any) {
      error.value = err.message || '获取业务闭环记录失败';
      businessLoopLogs.value = [];
      throw err;
    }
  };

  // 检查业务闭环完整性
  const checkBusinessLoopIntegrity = async (websiteId: string | number, date?: string) => {
    // 不设置全局 isLoading，避免影响其他加载状态
    error.value = null;
    try {
      const response = await trackingAPI.checkBusinessLoopIntegrity(websiteId, date);
      // 处理不同的响应格式：确保处理 records 字段
      let integrity: any = null;
      if (response?.data) {
        integrity = response.data;
      } else if (response) {
        integrity = response;
      }
      
      // 确保 integrity 对象有正确的结构
      if (integrity && !Array.isArray(integrity)) {
        businessLoopIntegrity.value = {
          isComplete: integrity.isComplete ?? false,
          totalSteps: integrity.totalSteps ?? (integrity.records?.length || 0),
          missingSteps: integrity.missingSteps || [],
          records: integrity.records || []
        };
      } else {
        businessLoopIntegrity.value = {
          isComplete: false,
          totalSteps: 0,
          missingSteps: [],
          records: []
        };
      }
      
      return businessLoopIntegrity.value;
    } catch (err: any) {
      error.value = err.message || '检查业务闭环完整性失败';
      businessLoopIntegrity.value = {
        isComplete: false,
        totalSteps: 0,
        missingSteps: [],
        records: []
      };
      throw err;
    }
  };

  // 清除业务闭环数据
  const clearBusinessLoopData = () => {
    businessLoopLogs.value = null;
    businessLoopIntegrity.value = null;
  };

  // 清除错误
  const clearError = () => {
    error.value = null;
  };

  return {
    websites,
    currentWebsite,
    websiteStats,
    businessLoopLogs,
    businessLoopIntegrity,
    logStats,
    isLoading,
    error,
    statsParams,
    fetchWebsites,
    createWebsite,
    updateWebsite,
    deleteWebsite,
    deleteAllWebsites,
    setCurrentWebsite,
    updateStatsParams,
    fetchWebsiteStats,
    getEmbedCode,
    fetchLogStats,
    fetchBusinessLoopLogs,
    checkBusinessLoopIntegrity,
    clearBusinessLoopData,
    clearError,
  };
});

